package com.Web.Class;

import com.DAO.Impl.ClassDAOImpl;
import com.DAO.Impl.ClassTypeImpl;
import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;

/**
 * @author 20x
 * @date 2024 - 12 -18
 **/
@WebServlet("/upClassStatus")
public class UpClassStatus extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();

        String weekOfMonth = req.getParameter("weekOfMonth");
        String newWeekOfMonth = req.getParameter("NewWeekOfMonth");
        int UpClassStatus = new ClassDAOImpl().UpdataClassStatus(weekOfMonth);
        if(UpClassStatus > 0){
            List<String> listClassType = new ClassTypeImpl().listClassType();
            String newData  = new ClassDAOImpl().slelectNewData();
            String Week = null;
            System.out.println(weekOfMonth+newWeekOfMonth+UpClassStatus+listClassType+newData);
            for (int i = 0; i < listClassType.size(); i++) {
                for (int j = 1; j <= 5; j++) {
                    switch (j){
                        case 1:Week="周一";break;
                        case 2:Week="周二";break;
                        case 3:Week="周三";break;
                        case 4:Week="周四";break;
                        case 5:Week="周五";break;
                    }
                    int count = new ClassDAOImpl().Inesertcoaches(newWeekOfMonth,Week,addDaysToDate(newData, j+2),listClassType.get(i));
                    if(count > 0){
                        out.write(gson.toJson("提交成功"));
                    }
                }
            }
        }


    }

    /**
     * Adds a number of days to a given date string.
     * 
     * @param dateStr the date string in the format "yyyy-MM-dd"
     * @param daysToAdd the number of days to add
     * @return the new date string after adding the days
     */
    public String addDaysToDate(String dateStr, int daysToAdd) {
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(dateStr, formatter);
            LocalDate newDate = date.plusDays(daysToAdd);
            return newDate.format(formatter);
        } catch (DateTimeParseException e) {
            System.err.println("Invalid date format: " + dateStr);
            return null;
        }
    }
}
